using B.S.BaseData.Api.Write.Application.Command.Procurements;
using B.S.BaseData.Domain;
using MediatR;
using SmartTracking.ErrorCode;
using SmartTracking.Infrastructure.Interfaces;

namespace B.S.BaseData.Api.Write.Application.CommandHandler.Procurements
{
    /// <summary>
    /// 删除采购命令处理器
    /// </summary>
    public class DeleteProcurementCommandHandler : IRequestHandler<DeleteProcurementCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<Procurement> procurement;

        public DeleteProcurementCommandHandler(IBaseRepository<Procurement> procurement)
        {
            this.procurement = procurement;
        }

        public async Task<ApiResult<int>> Handle(DeleteProcurementCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> res = new ApiResult<int>();

            try
            {
                var procurementRecord = procurement.GetAll().Where(x => x.ProcurementId == request.ProcurementId).FirstOrDefault();

                if (procurementRecord == null)
                {
                    res.Message = "采购记录不存在";
                    res.Code = ApiEnum.删除失败;
                    return res;
                }

                procurementRecord.IsDeleted = true;

                var r = await procurement.UpdateAsync(procurementRecord);

                if (r > 0)
                {
                    res.Message = "删除成功";
                    res.Code = ApiEnum.删除成功;
                    res.data = r;
                }
                else
                {
                    res.Message = "删除失败";
                    res.Code = ApiEnum.删除失败;
                }
            }
            catch (Exception ex)
            {
                res.Message = "删除失败: " + ex.Message;
                res.Code = ApiEnum.删除失败;
            }

            return res;
        }
    }
}

